package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.UserLocation;
import com.tanhua.domain.vo.UserLocationVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metric;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存或者更新
     */
    public void save(Double latiude, Double longitude, String address,Long userId) {
        //1、根据用户id查询位置信息
        Query query = new Query(Criteria.where("userId").is(userId));
        if(!mongoTemplate.exists(query, UserLocation.class)) {
            //2、如果不存在，保存
            UserLocation location = new UserLocation();
            location.setId(ObjectId.get());
            location.setUserId(userId);
            location.setAddress(address);
            location.setCreated(System.currentTimeMillis());
            location.setUpdated(System.currentTimeMillis());
            location.setLastUpdated(System.currentTimeMillis());
            GeoJsonPoint point = new GeoJsonPoint(latiude,longitude);
            location.setLocation(point);
            mongoTemplate.save(location);
        }else {
            //3、如果存在，更新
            Update update = new Update();
            update.set("address", address);
            update.set("updated",System.currentTimeMillis());
            GeoJsonPoint point = new GeoJsonPoint(latiude,longitude);
            update.set("update",point);
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }
    }

    @Override
    public List<UserLocationVo> searchNear(Long userId, Long miles) {
        //1、根据用户id，查询当前用户的位置
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        //2、指定查询的半径范围
        GeoJsonPoint location = userLocation.getLocation();
        Distance distance = new Distance(miles/1000, Metrics.KILOMETERS);
        //3、根据此半径画圆
        Circle circle = new Circle(location,distance); //圆点，半径
        //4、调用mongotemplate查询 List<UserLocation>
        Query nearQuery = new Query(
                Criteria.where("location").withinSphere(circle)
        );
        List<UserLocation> userLocations = mongoTemplate.find(nearQuery, UserLocation.class);
        //5、转化为List<UserLocationVo>
        return UserLocationVo.formatToList(userLocations);
    }
}
